//
//  PhotoBrowserViewController.swift
//  Weibo
//
//  Created by 孙明海 on 16/2/19.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 照片浏览器cell 可重用ID
private let PhotoBrowserCellID = "PhotoBrowserCellID"

/// 照片浏览器
class PhotoBrowserViewController: UIViewController {
    //MARK: - 监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func save() {
        let cell = collectionView.visibleCells()[0] as! PhotoBrowerViewCell
        guard let image = cell.imageView.image else {
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        let message = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(message)
    }
    /// 照片 url 数组
    private var urls: [NSURL]
    /// 当前选中图片的索引
    private var currentIndexPath: NSIndexPath
    
    //MARK: - 构造函数
    init(urls: [NSURL], indexPath: NSIndexPath) {
        self.urls = urls
        self.currentIndexPath = indexPath
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - 生命周期函数
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
        setupUI()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor(white: 0.9, alpha: 1)
        // 滚到指定的 cell
        collectionView.scrollToItemAtIndexPath(currentIndexPath, atScrollPosition: .Left, animated: true)
    }
    
    
    //MARK: - 懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowerViewLayout())
    /// 关闭按钮
    private lazy var closeButton: UIButton = UIButton(title: "关闭",fontSize: 14, color: UIColor.whiteColor(), backImageName: nil, backColor: UIColor.darkGrayColor())
    /// 保存按钮
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), backImageName: nil, backColor: UIColor.darkGrayColor())
    //MARK: - 自定义流水布局
    private class PhotoBrowerViewLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            let size = collectionView!.bounds.size
            itemSize = size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
            scrollDirection = .Horizontal
        }
    }
}
// MARK: - 设置控件
extension PhotoBrowserViewController {
    /// 设置UI
    private func setupUI() {
        //添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        //设置布局
        collectionView.frame = view.bounds
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
//            make.size.equalTo(CGSize(width: 100, height: 36))
            make.width.equalTo(100)
            make.height.equalTo(36)
        }
        saveButton.snp_makeConstraints { (make) -> Void in
//            make.size.equalTo(CGSizeMake(100, 36))
            make.width.equalTo(100)
            make.height.equalTo(36)
            make.right.equalTo(view.snp_right).offset(-28)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
        }
        
        // 注册点击事件
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        
        // 准备控件
        prepareCollectionView()
    }
    
    // 准备collectionView
    private func prepareCollectionView() {
        collectionView.registerClass(PhotoBrowerViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCellID)
        collectionView.dataSource = self
    }
}
// MARK: - UICollectionViewDataSource
extension PhotoBrowserViewController: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellID, forIndexPath: indexPath) as! PhotoBrowerViewCell
        cell.backgroundColor = UIColor.blackColor()
        cell.imageURL = urls[indexPath.item]
        cell.photoDelegate = self
        return cell
    }
}

// MARK: - PhotoBrowerViewCellDelegate
extension PhotoBrowserViewController: PhotoBrowerViewCellDelegate {
    func PhotoBrowerViewCellDidTapImage() {
        close()
    }
}
// MARK: - PhotoBrowerDismissDelegate
extension PhotoBrowserViewController: PhotoBrowerDismissDelegate {
    func imageViewForDismiss() -> UIImageView {
        let cell = collectionView.visibleCells()[0] as! PhotoBrowerViewCell
        return cell.imageView
    }
    func indexPathForDismiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems()[0]
    }
}